<template>
  <div class="chance-list-container">
    <!-- 搜索表单 -->
    <el-card class="search-container">
      <el-form
        :model="queryForm"
        ref="queryFormRef"
        :inline="true"
        label-width="80px"
        class="basic-search-form"
      >
        <el-form-item label="关键词">
          <el-input
            v-model="queryForm.keywords"
            placeholder="请输入机会名称或客户名称"
            clearable
            @keyup.enter="handleSearch"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="阶段">
          <el-select
            v-model="queryForm.stage"
            placeholder="请选择阶段"
            clearable
            style="width: 220px"
          >
            <el-option
              v-for="stage in stageOptions"
              :key="stage.id"
              :label="stage.title"
              :value="stage.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格和分页 -->
    <el-card class="data-table-container">
      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <el-button type="success" @click="handleAdd">新增机会</el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="selectedChances.length === 0"
        >
          批量删除
        </el-button>
      </div>

      <!-- 销售机会表格 -->
      <el-table
        :data="chanceList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
        class="custom-table"
        height="calc(100vh - 380px)"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="机会名称" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <span class="text-ellipsis">{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="customer_name"
          label="客户名称"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="expected_order_amount" label="预计金额" width="120">
          <template #default="scope">¥{{ scope.row.expected_order_amount }}</template>
        </el-table-column>
        <el-table-column prop="stage_text" label="阶段" width="120" show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-if="scope.row.stage === 1" type="info">初步接触</el-tag>
            <el-tag v-else-if="scope.row.stage === 2" type="info">需求分析</el-tag>
            <el-tag v-else-if="scope.row.stage === 3" type="warning">方案报价</el-tag>
            <el-tag v-else-if="scope.row.stage === 4" type="danger">商务谈判</el-tag>
            <el-tag v-else-if="scope.row.stage === 5" type="success">成交</el-tag>
            <el-tag v-else-if="scope.row.stage === 6" type="info">失败</el-tag>
            <span v-else>{{ scope.row.stage_text || '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="discovery_time"
          label="发现时间"
          width="180"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.discovery_time ? formatDate(scope.row.discovery_time) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="admin_name" label="负责人" width="120" show-overflow-tooltip />
        <el-table-column
          prop="create_time"
          label="创建时间"
          width="180"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.create_time ? formatDateTime(scope.row.create_time * 1000) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" plain @click="handleView(scope.row)">
              查看
            </el-button>
            <el-dropdown>
              <el-button size="small" plain>
                更多
                <el-icon><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleEdit(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(scope.row)" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <BasePagination
          v-model="queryForm.page"
          v-model:page-size="queryForm.limit"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 销售机会详情抽屉 -->
    <GlobalDrawer
      v-model="detailDrawerVisible"
      title="机会详情"
      size="60%"
      :show-footer-buttons="false"
    >
      <div class="drawer-content">
        <el-descriptions :column="2" size="large" border>
          <el-descriptions-item label="机会名称">{{ currentChance.title }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentChance.customer_name }}
          </el-descriptions-item>
          <el-descriptions-item label="阶段">
            <el-tag v-if="currentChance.stage === 1" type="info">初步接触</el-tag>
            <el-tag v-else-if="currentChance.stage === 2" type="info">需求分析</el-tag>
            <el-tag v-else-if="currentChance.stage === 3" type="warning">方案报价</el-tag>
            <el-tag v-else-if="currentChance.stage === 4" type="danger">商务谈判</el-tag>
            <el-tag v-else-if="currentChance.stage === 5" type="success">成交</el-tag>
            <el-tag v-else-if="currentChance.stage === 6" type="info">失败</el-tag>
            <span v-else>{{ currentChance.stage_text || '未知' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="预计金额">
            ¥{{ currentChance.expected_order_amount }}
          </el-descriptions-item>
          <el-descriptions-item label="发现时间">
            {{ currentChance.discovery_time ? formatDate(currentChance.discovery_time) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="预计成交时间">
            {{ currentChance.expected_time ? formatDate(currentChance.expected_time) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="负责人">{{ currentChance.admin_name }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentChance.create_time ? formatDateTime(currentChance.create_time * 1000) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ currentChance.content }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </GlobalDrawer>

    <!-- 新增/编辑销售机会抽屉 -->
    <GlobalDrawer
      v-model="drawerVisible"
      :title="chanceOperationMode === 'add' ? '新增机会' : '编辑机会'"
      size="60%"
      @confirm="handleSubmit"
    >
      <div class="drawer-content">
        <el-form
          :model="chanceForm"
          :rules="chanceRules"
          ref="chanceFormRef"
          label-width="100px"
          class="chance-form"
        >
          <el-form-item label="机会名称" prop="title">
            <el-input v-model="chanceForm.title" placeholder="请输入机会名称" />
          </el-form-item>
          <el-form-item label="客户" prop="cid">
            <el-select
              v-model="chanceForm.cid"
              placeholder="请输入客户名称搜索"
              filterable
              remote
              :remote-method="remoteSearchCustomers"
              :loading="customerLoading"
            >
              <el-option
                v-for="customer in customerOptions"
                :key="customer.id"
                :label="customer.name"
                :value="customer.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="阶段" prop="stage">
            <el-select v-model="chanceForm.stage" placeholder="请选择阶段">
              <el-option
                v-for="stage in stageOptions"
                :key="stage.id"
                :label="stage.title"
                :value="stage.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预计金额" prop="expected_order_amount">
            <el-input
              v-model.number="chanceForm.expected_order_amount"
              placeholder="请输入预计金额"
              type="number"
            />
          </el-form-item>
          <el-form-item label="发现日期" prop="discovery_time">
            <el-date-picker
              v-model="chanceForm.discovery_time"
              type="date"
              placeholder="请选择发现日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="预计成交日期" prop="expected_time">
            <el-date-picker
              v-model="chanceForm.expected_time"
              type="date"
              placeholder="请选择预计成交日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="描述内容" prop="content">
            <el-input
              v-model="chanceForm.content"
              placeholder="请输入描述内容"
              type="textarea"
              :rows="4"
            />
          </el-form-item>
        </el-form>
      </div>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElForm } from 'element-plus'
  import axios from '@/utils/request'
  import type { ApiResponse } from '@/types/api'
  import { formatDate, formatDateTime } from '@/utils/format'
  import BasePagination from '@/components/base/BasePagination.vue'
  import { GlobalDrawer } from '@/components/common'
  import { ArrowDown } from '@element-plus/icons-vue'
  import { customerApi } from '@/api/customer'

  // 表单引用
  const queryFormRef = ref<InstanceType<typeof ElForm>>()
  const chanceFormRef = ref<InstanceType<typeof ElForm>>()

  // 路由
  const router = useRouter()

  // 搜索表单数据
  const queryForm = reactive({
    page: 1,
    limit: 10,
    keywords: '',
    stage: '',
  })

  // 下拉选项数据
  const customerOptions = ref<any[]>([])
  const stageOptions = ref<any[]>([])

  // 表格数据
  const chanceList = ref<any[]>([])
  const total = ref(0)
  const loading = ref(false)
  const selectedChances = ref<any[]>([])

  // 抽屉状态
  const detailDrawerVisible = ref(false)
  const drawerVisible = ref(false)
  const chanceOperationMode = ref<'add' | 'edit'>('add')

  // 当前选中的商机
  const currentChance = ref<Record<string, any>>({})

  // 加载状态
  const customerLoading = ref(false)

  // 商机表单数据
  const chanceForm = reactive({
    title: '',
    cid: '',
    stage: '',
    expected_order_amount: 0,
    discovery_time: '',
    expected_time: '',
    content: '',
  })

  // 表单验证规则
  const chanceRules = {
    title: [{ required: true, message: '请输入机会名称', trigger: 'blur' }],
    cid: [{ required: true, message: '请选择客户', trigger: 'change' }],
    stage: [{ required: true, message: '请选择阶段', trigger: 'change' }],
    expected_order_amount: [{ required: true, message: '请输入预计金额', trigger: 'blur' }],
    discovery_time: [{ required: true, message: '请选择发现时间', trigger: 'change' }],
  }

  // 获取商机列表
  const getChanceList = async () => {
    try {
      loading.value = true
      const response: ApiResponse<any> = await axios.get('/api/customer/chance/list', {
        params: queryForm,
      })
      if (response.code === 0) {
        chanceList.value = response.data.list
        total.value = response.data.total
      } else {
        ElMessage.error(response.msg || '获取商机列表失败')
      }
    } catch (error) {
      ElMessage.error('获取商机列表失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索客户
  const remoteSearchCustomers = async (query: string) => {
    try {
      customerLoading.value = true
      const response: ApiResponse<any[]> = await axios.get('/api/customer/search', {
        params: { keyword: query },
      })
      if (response.code === 0) {
        customerOptions.value = response.data
      } else {
        ElMessage.error(response.msg || '搜索客户失败')
      }
    } catch (error) {
      ElMessage.error('搜索客户失败')
    } finally {
      customerLoading.value = false
    }
  }

  // 获取阶段选项
  const getStageOptions = async () => {
    try {
      const response: ApiResponse<any[]> = await customerApi.getChanceStageOptions()
      if (response.code === 0) {
        stageOptions.value = response.data
      } else {
        ElMessage.error(response.msg || '获取阶段选项失败')
      }
    } catch (error) {
      ElMessage.error('获取阶段选项失败')
    }
  }

  // 搜索
  const handleSearch = () => {
    queryForm.page = 1
    getChanceList()
  }

  // 重置
  const handleReset = () => {
    Object.assign(queryForm, {
      keywords: '',
      stage: '',
      page: 1,
    })
    getChanceList()
  }

  // 新增机会
  const handleAdd = () => {
    chanceOperationMode.value = 'add'
    // 创建新对象而不是修改现有对象，确保清除所有额外字段（如id）
    Object.keys(chanceForm).forEach(key => {
      delete chanceForm[key as keyof typeof chanceForm]
    })
    Object.assign(chanceForm, {
      title: '',
      cid: '',
      stage: '',
      expected_order_amount: 0,
      discovery_time: '',
      expected_time: '',
      content: '',
    })
    drawerVisible.value = true
  }

  // 查看机会
  const handleView = (row: any) => {
    currentChance.value = row
    detailDrawerVisible.value = true
  }

  // 编辑机会
  const handleEdit = (row: any) => {
    chanceOperationMode.value = 'edit'

    // 深拷贝row对象，避免直接修改源数据
    const rowData = { ...row }

    // 将时间戳转换为日期字符串格式
    if (rowData.discovery_time) {
      const discoveryDate = new Date(rowData.discovery_time)
      rowData.discovery_time =
        discoveryDate.getFullYear() +
        '-' +
        String(discoveryDate.getMonth() + 1).padStart(2, '0') +
        '-' +
        String(discoveryDate.getDate()).padStart(2, '0')
    }
    if (rowData.expected_time) {
      const expectedDate = new Date(rowData.expected_time)
      rowData.expected_time =
        expectedDate.getFullYear() +
        '-' +
        String(expectedDate.getMonth() + 1).padStart(2, '0') +
        '-' +
        String(expectedDate.getDate()).padStart(2, '0')
    }

    // 如果有客户ID和客户名称，但customerOptions中不包含该客户，直接添加到选项中
    if (
      rowData.cid &&
      rowData.customer_name &&
      !customerOptions.value.some((item: any) => item.id === rowData.cid)
    ) {
      // 直接使用rowData中的客户名称，避免额外的接口调用
      customerOptions.value.unshift({
        id: rowData.cid,
        name: rowData.customer_name,
      })
    }

    // 保存当前编辑的机会数据，用于构建API URL
    currentChance.value = rowData

    Object.assign(chanceForm, rowData)
    drawerVisible.value = true
  }

  // 删除机会
  const handleDelete = async (row: any) => {
    try {
      const response: ApiResponse<any> = await axios.delete(`/api/customer/chance/delete/${row.id}`)
      if (response.code === 0) {
        ElMessage.success('删除成功')
        getChanceList()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedChances.value.length === 0) return
    try {
      const ids = selectedChances.value.map(item => item.id)
      const response: ApiResponse<any> = await axios.delete('/api/customer/chance/batch-delete', {
        data: { ids },
      })
      if (response.code === 0) {
        ElMessage.success('批量删除成功')
        getChanceList()
        selectedChances.value = []
      } else {
        ElMessage.error(response.msg || '批量删除失败')
      }
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  }

  // 分页变更
  const handleCurrentChange = (page: number) => {
    queryForm.page = page
    getChanceList()
  }

  // 页大小变更
  const handleSizeChange = (limit: number) => {
    queryForm.limit = limit
    getChanceList()
  }

  // 选择变更
  const handleSelectionChange = (val: any[]) => {
    selectedChances.value = val
  }

  // 提交表单
  const handleSubmit = async () => {
    try {
      const apiUrl =
        chanceOperationMode.value === 'add'
          ? '/api/customer/chance/add'
          : `/api/customer/chance/edit/${currentChance.value.id}`
      const method = chanceOperationMode.value === 'add' ? 'post' : 'put'

      // 复制表单数据，但排除不需要提交的字段
      const { customer_name, admin_name, stage_text, ...submitData }: Record<string, any> = {
        ...chanceForm,
      }
      // 将日期字符串转换为时间戳（秒级）
      if (submitData.discovery_time) {
        submitData.discovery_time = Math.floor(new Date(submitData.discovery_time).getTime() / 1000)
      }
      if (submitData.expected_time) {
        submitData.expected_time = Math.floor(new Date(submitData.expected_time).getTime() / 1000)
      }

      const response: ApiResponse<any> = await axios[method](apiUrl, submitData)
      if (response.code === 0) {
        ElMessage.success(chanceOperationMode.value === 'add' ? '新增成功' : '编辑成功')
        drawerVisible.value = false
        getChanceList()
      } else {
        ElMessage.error(
          response.msg || (chanceOperationMode.value === 'add' ? '新增失败' : '编辑失败')
        )
      }
    } catch (error) {
      ElMessage.error(chanceOperationMode.value === 'add' ? '新增失败' : '编辑失败')
    }
  }

  // 初始化
  const init = async () => {
    await Promise.all([getChanceList(), getStageOptions()])
  }

  // 在组件挂载时初始化
  onMounted(() => {
    init()
  })
</script>
